package com.example.wifi_demo;

import android.os.Build;

import androidx.annotation.RequiresApi;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {

    /**
     * 秘钥 加密算法
     */
    private static final String KEY_ALGORITHM="RSA";

    /**
     * 加密/解密算法-工作模式-填充模式
     */
    //private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    private static final String CIPHER_ALGORITHM="RSA/ECB/PKCS1Padding";

    /**
     * 签名的算法
     */
    private static final String SIGNATURE_ALGORITHM="MD5withRSA";


    /**
     * 密码对中公钥的key
     */
    private static final String PUBLIC_KEY="RSAPublicKey";

    /**
     * 密码对中，私钥的key
     */
    private static final String PRIVATE_KEY="RSAPrivateKey";


    /**
     * RSA 最大的加密明文大小
     */
    private static final int MAX_ENCRIPT_BLOCK=128;

    /**
     * RSA 最大的解密文件大小
     *      * RSA 位数 如果采用1024 上面最大加密和最大解密则须填写: 117 128
     *      * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写: 245 256
     */
    private static final int MAX_DECRIPT_BLOCK=256;

    /**
     * 初始化密钥对生成器时，指定秘钥的整数值，
     */
    private static final int KEY_PAIR_INIT_SIZE=2048;

    private static final char[] HEX_CHAR =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 将bytes进行Base64编码
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String encriptToBase64(byte[] bytes){
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 把Key通过Base64解码成byte[],
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static byte[] decriptyFromBase64(String key){
        return Base64.getDecoder().decode(key);
    }

    /**
     * 获取公钥字符串
     */
    public static String getPublicKeyStr(Map<String,Object> keyMap) throws Exception{
        Key key=(Key) keyMap.get(PUBLIC_KEY);
        return encriptToBase64(key.getEncoded());
    }

    /**
     * 获取私钥字符串
     */
    public static String getPrivateKeyStr(Map<String,Object> keyMap) throws Exception{
        Key key=(Key) keyMap.get(PRIVATE_KEY);
        return encriptToBase64(key.getEncoded());
    }

    /**
     * 获取公钥
     */
    public static PublicKey getPublicKey(String key) throws Exception{
        byte[] keyBytes=decriptyFromBase64(key);
        X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey=keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 获取私钥
     */
    public static PrivateKey getPrivateKey(String key) throws Exception{
        byte[] keyBytes=decriptyFromBase64(key);
        Security.addProvider(new BouncyCastleProvider());
        //Security.addProvider(new BouncyCastlePQCProvider());
        PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey=keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
    /**
     * 将byte[]转换为16进制字符串
     *
     * @param bytes 待转换byte[]
     * @return 转换后的字符串
     */
    public static String bytesToHex(byte[] bytes) {
        //一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for (byte b : bytes) { // 使用除与取余进行转换
            if (b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }
        return new String(buf);
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str 待转换字符串
     * @return 转换后的byte[]
     */
    public static byte[] hexToBytes(String str) {
        if (str == null || "".equals(str.trim())) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    /**
     * 生成签名
     * @Param data : 待签名的内容
     * @Param: 私钥参数
     */
    public static String sign(byte[] data,String privateKeyParam) throws Exception{
        //PrivateKey privateKey=getPrivateKey(new String(hexToBytes(privateKeyParam)));
        PrivateKey privateKey=getPrivateKey(privateKeyParam);
        Signature sig=Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(privateKey);
        sig.update(data);
        String result=bytesToHex(sig.sign());
        return result;
    }

    /**
     * 验证签名
     * @Param data: 待验证的原文
     * @Param sign: 待验证的签名
     * @Param  publicKeyStr: 公钥
     */
    public static boolean verify(byte[] data,String sign,String publicKeyStr) throws Exception{
        //PublicKey publicKey=getPublicKey(new String(hexToBytes(publicKeyStr)));
        PublicKey publicKey=getPublicKey(publicKeyStr);
        Signature sig=Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(data);
        return sig.verify(hexToBytes(sign));
    }


    /**
     * RSA 加密
     * @Param plainText : 待加密的内容
     * @Param publicKeyStr : 公钥
     * @Return 加密后的字符串，16进制
     * @Exception 抛出异常
     */
    public static String encrypt(byte[] plainText,String publicKeyStr) throws Exception{
        PublicKey publicKey=getPublicKey(publicKeyStr);
        Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);

        int inputLen=plainText.length;
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        int offset=0;
        int i=0;
        byte[] cache;
        while(inputLen-offset>0){
            if(inputLen-offset>MAX_ENCRIPT_BLOCK){
                cache=cipher.doFinal(plainText,offset,MAX_ENCRIPT_BLOCK);
            }else{
                cache=cipher.doFinal(plainText,offset,inputLen-offset);
            }
            out.write(cache,0,cache.length);
            i++;
            offset=i*MAX_ENCRIPT_BLOCK;
        }
        byte[] encriptText=out.toByteArray();
        out.close();
        return bytesToHex(encriptText);
    }

    /**
     * 解密
     * @Param encritpTextHex: 待解密的字符串
     * @Param privateKeyStr: 私钥
     */
    public static String decrypt(String encriptTextHex,String privateKeyStr) throws Exception{
        byte[] encriptText=hexToBytes(encriptTextHex);
        PrivateKey privateKey=getPrivateKey(privateKeyStr);
        Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);

        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] cache;

        int inputLen=encriptText.length;
        int offset=0;
        int i=0;
        while(inputLen-offset>0){
            if(inputLen-offset>MAX_DECRIPT_BLOCK){
                cache=cipher.doFinal(encriptText,offset,MAX_DECRIPT_BLOCK);
            }else{
                cache=cipher.doFinal(encriptText,offset,inputLen-offset);
            }
            out.write(cache,0,cache.length);
            i++;
            offset=i*MAX_DECRIPT_BLOCK;
        }
        byte[] plainText=out.toByteArray();
        out.close();
        return new String(plainText);
    }

    /**
     * 初始化密码
     */
    public static Map<String,Object> initKey() throws Exception{
        KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(KEY_PAIR_INIT_SIZE);
        KeyPair keyPair=keyPairGenerator.generateKeyPair();

        RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey privateKey=(RSAPrivateKey)keyPair.getPrivate();
        Map<String,Object> map=new HashMap<>(2);
        map.put(PUBLIC_KEY,publicKey);
        map.put(PRIVATE_KEY,privateKey);
        return map;
    }

}
